﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace GUI.PhieuTTCuaKH
{
    public partial class frmXuLy : Form // VƯƠNG TRÍ LỢI
    {

        #region Contructor
        public bool kiemtra1 = false;
        string hanhdong;
        bool checkClose = false;
        Entities.PhieuTTCuaKH phieuthanhtoankhachhang;
        Entities.PhieuTTCuaKH temp;
        Entities.PhieuTTCuaKH phieuthanhtoankh;

        Entities.ChiTietPhieuTTCuaKH[] hienthi1;
        Entities.ChiTietPhieuTTCuaKH[] param;
        Entities.ChiTietPhieuTTCuaKH save;
        private Entities.GiaTriCombox[] DoiTuong;
        Entities.ChiTietPhieuTTCuaKH[] checklistview;

        string makho = "";
        string tenkho = "";
        DateTime date;

        public static string thanhtoansaukhilapphieu;
        public static string thanhtoanmoi;
        #endregion

        #region check permission
        public bool CheckPer()
        {
            return true;
        }
        #endregion

        #region Check conflicts

        string maphieuthanhtoankhachhang = "";
        // Check Conflic Insert
        public bool CheckConflicInsert()
        {
            try
            {
                Entities.GetID id = new Entities.GetID();
                id.TableName = "PhieuTTCuaKH";
                Entities.GetID get = Common.StaticVariable.InterfaceObject.SelectID(id);
                maphieuthanhtoankhachhang = get.ColumnName;
                if (maphieuthanhtoankhachhang == SbiMaPTTKH.Text.ToString())
                {
                    return true;
                }
                return false;
            }
            catch
            {
                return true;
            }
        }

        //Check Conflic Update
        public bool CheckConflicUpdate()
        {
            try
            {
                Entities.PhieuTTCuaKH[] mangchitiet = Common.StaticVariable.InterfaceObject.SelectPhieuTTKH();

                for (int i = 0; i < mangchitiet.Length; i++)
                {
                    if (mangchitiet[i].MaPhieuTTCuaKH == SbiMaPTTKH.Text.ToString())
                    {
                        return kiemtra(mangchitiet[i]);
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        // kiểm tra
        public bool kiemtra(Entities.PhieuTTCuaKH pttkh)
        {
            try
            {
                bool kt = true;
                if (temp.MaKhachHang != pttkh.MaKhachHang)
                {
                    txtMaKH.Text = pttkh.MaKhachHang;
                    kt = false;
                }
                //if (temp.TenKhachHang != pttkh.TenKhachHang)
                //{
                //    txtTenKH.Text = pttkh.TenKhachHang;
                //    kt = false;
                //}
                if (temp.TongThanhToan != pttkh.TongThanhToan)
                {
                    txtNoHienThoi.Text = pttkh.TongThanhToan;
                    kt = false;
                }
                if (temp.NguoiNop != pttkh.NguoiNop)
                {
                    txtNguoiNopTien.Text = pttkh.NguoiNop;
                    kt = false;
                }

                if (temp.GhiChu != pttkh.GhiChu)
                {
                    txtGhiChu.Text = pttkh.GhiChu.ToString();
                    kt = false;
                }
                return kt;
            }
            catch
            {
                return true;

            }

        }

        #endregion

        #region Nghiệp vụ

        // thoát
        public void Thoat()
        {
            try
            {
                if (hanhdong == Common.Constants.Insert)
                { kiemtra1 = true; }
                checkClose = false;
                this.Close();
            }
            catch
            {
            }
        }

        // thêm
        public void Them()
        {
            try
            {
                if (Entitystatic.ViewFile().MaKho == "NULL" || Entitystatic.ViewFile().MaKho == string.Empty)
                {
                    MessageBox.Show("Bạn hãy cài kho trước khi thêm mới");
                    return;
                }

                if (checklistview == null || checklistview.Length == 0)
                {
                    MessageBox.Show("Hãy chọn chi tiết hóa đơn ?", Common.MSG.TieuDe);
                    txtMaHoaDon.Focus();
                    return;
                }
                // lấy giá trị thanh toán trong listview dùng để cộng với giá trị thanh toán sau khi lập trong HDBanBuon sau đó update lại giá trị vào trường này
                double k = 0;
                Entities.ChiTietPhieuTTCuaKH[] f = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                for (int i = 0; i < f.Length; i++)
                {
                    k += double.Parse(f[i].ThanhToan.ToString());
                    lbTongThanhToan.Text = k.ToString();
                }

                phieuthanhtoankhachhang = XuLyObject(Common.Constants.Insert);

                // check object 
                if (phieuthanhtoankhachhang == null)
                {
                    return;
                }

               //
                if (CheckConflicInsert())
                {
                    MessageBox.Show(Common.MSG.MSG5(phieuthanhtoankhachhang.MaPhieuTTCuaKH), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    SbiMaPTTKH.Text = getID();
                    lbMaPhieuTTKH.Text = maphieuthanhtoankhachhang;
                    return;
                }

                //check insert
                if(!Common.StaticVariable.InterfaceObject.InsertUpdatePhieuTTKH(phieuthanhtoankhachhang))
                {
                    return;
                }

                Entities.ChiTietPhieuTTCuaKH[] listview = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                if (listview == null)
                {
                    return;
                }
                //  insert
                Common.StaticVariable.InterfaceObject.InsertUpdateChiTietPhieuTTCuaKH(listview);


                //update thanh toán sau khi lập phiếu của HBBanBuon (Phiếu Thu ) or HD KH Trả Lại Ban Buôn ( Phiếu Chi)
                Update();

                //  update dư nợ khách hàng
                UpdateDuNoKH();

                checkClose = true;
                this.Close();

            }
            catch
            {
            }

        }

        // update giá của thanh toán sau khi lập phiếu nếu insert thành công
        public void Update()
        {
            try
            {
                Entities.ChiTietPhieuTTCuaKH[] listview = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                if (listview == null)
                {
                    return;
                }
                for (int i = 0; i < listview.Length; i++)
                {
                    if (cbbLoaiPhieu.Text == "Phiếu Thu")
                    { 
                        // update Hóa Đơn Bán buôn
                        UpdateThanhToanSauKhiLapPhieu(listview[i].MaHDBanHang, listview[i].ThanhToanMoi);
                    }
                    else
                    {
                        // update Trả Lại Khách Hàng
                        UpdateThanhToanSauKhiLapPhieu(listview[i].MaHDBanHang, listview[i].ThanhToanMoi, "KHTL");
                    }
                }
            }
            catch
            {
            }
        }

        // Method updatedư nợ của khách hàng
        public void UpdateDuNoKH()
        {
            try
            {
                Entities.ChiTietCongNoKH temp = new Entities.ChiTietCongNoKH("1",
                   txtMaKH.Text
                    , makho, TongTienTrongListview.ToString(), false);
                Entities.ChiTietCongNoKH[] chitiet = Common.StaticVariable.InterfaceObject.SelectChiTietCongNoKH(temp);


                if (cbbLoaiPhieu.Text == "Phiếu Thu")
                {
                    if (chitiet != null && chitiet.Length != 0)
                        temp.HanhDong = "ThanhToan"; // Tru
                    else
                        temp.HanhDong = "Insert";
                    Common.StaticVariable.InterfaceObject.InsertUpdateChiTietCongNoKH(temp);

                }
                else
                {
                    if (chitiet != null && chitiet.Length != 0)
                        temp.HanhDong = "Update"; // Cong
                    else
                        temp.HanhDong = "Insert";
                    Common.StaticVariable.InterfaceObject.InsertUpdateChiTietCongNoKH(temp);

                }
            }
            catch
            {

            }
        }

        void In()
        {
            try
            {
                if (phieuthanhtoankh == null)
                {
                    return;
                }
                this.Enabled = false;
                Entities.ChiTietPhieuTTCuaKH[] ctpttckh = Common.StaticVariable.InterfaceObject.SelectChiTietPhieuTTKH(phieuthanhtoankh.MaPhieuTTCuaKH);
                Entities.KhachHang kh = new Entities.KhachHang();
                kh.MaKhachHang = phieuthanhtoankh.MaKhachHang;
                kh = Common.StaticVariable.InterfaceObject.Select_KhachHang(kh);
                // true là chi
                if (phieuthanhtoankh.LoaiPhieu)
                {
                    int sotang = 0;
                    Entities.BCPhieuThanhToanKhachHangPHIEUCHI[] bc = new Entities.BCPhieuThanhToanKhachHangPHIEUCHI[ctpttckh.Length];
                    foreach (Entities.ChiTietPhieuTTCuaKH item in ctpttckh)
                    {
                        bc[sotang] = new Entities.BCPhieuThanhToanKhachHangPHIEUCHI();
                        bc[sotang].NgayHD = phieuthanhtoankh.NgayLap.ToString("dd/MM/yyyy");
                        bc[sotang].SoHD = phieuthanhtoankh.MaPhieuTTCuaKH;
                        bc[sotang].STT = sotang + 1;
                        bc[sotang].ThanhToan = double.Parse(item.ThanhToan);
                        bc[sotang].TongTienHD = double.Parse(item.TongTienThanhToan);
                        bc[sotang].SoTienNo = double.Parse(item.SoNo);

                        sotang++;
                    }

                    BaoCao.frmBaoCaorpt frm = new BaoCao.frmBaoCaorpt(bc, kh, phieuthanhtoankh);
                    if (frm.kiemtra)
                    {
                        frm.ShowDialog();
                        frm.kiemtra = false;
                    }

                }
                else
                {
                    int sotang = 0;
                    Entities.BCPhieuThanhToanKhachHangPHIEUTHU[] bc = new Entities.BCPhieuThanhToanKhachHangPHIEUTHU[ctpttckh.Length];
                    foreach (Entities.ChiTietPhieuTTCuaKH item in ctpttckh)
                    {
                        bc[sotang] = new Entities.BCPhieuThanhToanKhachHangPHIEUTHU();
                        bc[sotang].NgayHoaDon = phieuthanhtoankh.NgayLap.ToString("dd/MM/yyyy");
                        bc[sotang].SoHoaDon = phieuthanhtoankh.MaPhieuTTCuaKH;
                        bc[sotang].STT = sotang + 1;
                        bc[sotang].ThanhToan = double.Parse(item.ThanhToan);
                        bc[sotang].TongTienHoaDon = double.Parse(item.TongTienThanhToan);
                        bc[sotang].SoTienNo = double.Parse(item.SoNo);
                        sotang++;
                    }
                    BaoCao.frmBaoCaorpt frm = new BaoCao.frmBaoCaorpt(bc, kh, phieuthanhtoankh);
                    if (frm.kiemtra)
                    {
                        frm.ShowDialog();
                        frm.kiemtra = false;
                    }
                }
                this.Enabled = true;
            }
            catch
            {
            }
        }

        #endregion

        #region Sự kiện của windown

        private void frmXuLy_Load(object sender, EventArgs e)
        {
            try
            {
                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                makho = kho.MaKho;
                tenkho = kho.TenKho;
                //  Status Bar
               
                btnThoat.MouseDown += new MouseEventHandler(MouseDown_Chung);
                btnGhiLai.MouseDown += new MouseEventHandler(MouseDown_Chung);
                btnIn.MouseDown += new MouseEventHandler(MouseDown_Chung);

                cbbLoaiPhieu.SelectedValueChanged += new EventHandler(cbbLoaiPhieu_SelectionChanged);
                //
                txtMaKH.Focus();
                lblTenNhanVien.Text = UtilitiesVariable.User.TenDangNhap;

                dgvHienThi.CellClick +=new DataGridViewCellEventHandler(dgvHienThi_CellClick);
                dgvHienThi.CellDoubleClick += new DataGridViewCellEventHandler(dgvHienThi_CellDoubleClick);
            }
            catch
            {
            }

        }

        void cbbLoaiPhieu_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                dgvHienThi.DataSource = null;
                txtMaHoaDon.Text = "<F4 - Tra cứu>";
                txtTongTien.Text = txtSoTienNo.Text = txtThanhToan.Text = "0";
            }
            catch
            {
            }
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyCode)
                {
                    case Keys.F2:
                        {
                            if (hanhdong == Common.Constants.Insert)
                            {
                                checklistview = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                                Them();
                            }
                            break;
                        }

                    case Keys.Escape:
                        {
                            Thoat();
                            break;
                        }
                }
            }
            catch
            {

            }

        }

        private void Window_Closing(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (!checkClose)
                    if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        e.Cancel = checkClose;
                    }
                    else
                        e.Cancel = !checkClose;
                else
                {
                    if (!kiemtra1)
                            Select(hanhdong);

                }

            }
            catch
            {
            }
        }

        public delegate void SelectData(string hanhdong);
        public SelectData Select;

        public Entities.ChiTietPhieuTTCuaKH[] HienThiChiTiet(Entities.PhieuTTCuaKH maphieuTTKH)
        {
            try
            {
                ArrayList array = new ArrayList();
                Entities.ChiTietPhieuTTCuaKH[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietPhieuTTKH1();
                foreach (Entities.ChiTietPhieuTTCuaKH item in temp)
                {
                    if (item.MaPhieuTTCuaKH == maphieuTTKH.MaPhieuTTCuaKH)
                        array.Add(item);
                }
                Entities.ChiTietPhieuTTCuaKH[] chitietchinhsachgiahang = (Entities.ChiTietPhieuTTCuaKH[])array.ToArray(typeof(Entities.ChiTietPhieuTTCuaKH));
                return chitietchinhsachgiahang;
            }
            catch { return new Entities.ChiTietPhieuTTCuaKH[0]; }
        }

        public Entities.ChiTietPhieuTTCuaKH[] HienThi()
        {
            try
            {
                ArrayList array = new ArrayList();
                Entities.ChiTietPhieuTTCuaKH[] chitietkhuyenmaitanghang = Common.StaticVariable.InterfaceObject.SelectChiTietPhieuTTKH1();
                return chitietkhuyenmaitanghang;
            }
            catch
            {
                return new Entities.ChiTietPhieuTTCuaKH[0];

            }
        }
        #endregion

        #region Combobox

        // giá trị của loại phiếu
        private void GetDataComBoLoaiPhieu()
        {
            try
            {
                DoiTuong = new Entities.GiaTriCombox[2];
                Entities.GiaTriCombox row = new Entities.GiaTriCombox();
                row.TenCotTenHienThi = "False";
                row.TenCotKhoaChinh = "Phiếu Thu";
                DoiTuong[0] = row;
                Entities.GiaTriCombox row2 = new Entities.GiaTriCombox();
                row2.TenCotTenHienThi = "True";
                row2.TenCotKhoaChinh = "Phiếu Chi";
                DoiTuong[1] = row2;
                Common.Utilities.XuLyComboBox(cbbLoaiPhieu, DoiTuong, Common.Constants.GiaTriCacForm.CotKhoaChinh, Common.Constants.GiaTriCacForm.CotTenHienThi);
                 
                cbbLoaiPhieu.SelectedIndex = 0;
            }
            catch
            { }
        }

        // display on combobox with condition địa điểm
        public void HienThiComBoBoxLoaiPhieu(string lp)
        {
            for (int i = 0; i < cbbLoaiPhieu.Items.Count; i++)
            {
                Entities.GiaTriCombox id = (Entities.GiaTriCombox)cbbLoaiPhieu.Items[i];
                if (id.TenCotTenHienThi == lp)
                {
                    cbbLoaiPhieu.SelectedIndex = i;
                    break;
                }
                else
                { continue; }
            }
        }

        #endregion

        #region Hien thi listview

        public bool ValidateDatagrid()
        {
            try
            {
                if (txtMaHoaDon.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHoaDon.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHoaDon.Focus();
                    return false;
                }
                if (txtTongTien.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbTongTien.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtTongTien.Focus();
                    return false;
                }
                if (txtThanhToan.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbThanhToan.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtThanhToan.Focus();
                    return false;
                }
                if (txtSoTienNo.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbSoTienNo.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtSoTienNo.Focus();
                    return false;
                }

                return true;
            }
            catch
            {

                return true;
            }

        }

        public void Add_GridView()
        {
            try
            {
                if (Entitystatic.ViewFile().MaKho == "NULL" || Entitystatic.ViewFile().MaKho == string.Empty)
                {
                    MessageBox.Show(Common.MSG.MSG13("Chưa có kho"), Common.MSG.TieuDe);
                    return;
                }

                if (txtMaKH.Text.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaKH.Text.ToString()), Common.MSG.TieuDe);
                    txtMaKH.Focus();
                    return;
                }

                if (ValidateDatagrid())
                {
                    if (txtThanhToan.Text != "" && txtThanhToan.Text != "0")
                    {
                        maHDBanbuon = txtMaHoaDon.Text;
                        mahanghoa = txtMaHoaDon.Text;
                        thanhtoanmoi = (Convert.ToDouble(txtThanhToan.Text) + Convert.ToDouble(ThanhToanKhiLapPhieu1(maHDBanbuon))).ToString();

                        NewRow();
                        TongTienHDNhap();
                        txtMaHoaDon.Text = "";
                        txtTongTien.Text = "";
                        txtSoTienNo.Text = "";
                        txtThanhToan.Text = "";
                        txtMaHoaDon.Focus();
                        txtMaHoaDon.Text = "<F4 - Tra cứu>";
                        //lbTongBanGhi.Text = Common.Constants.TongSo + dgvHienThi.Items.Count;

                    }

                }
            }
            catch
            { }
        }

        public void txtThanhToan_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    Add_GridView();
                }
            }
            catch { }
        }

        double TongTienTrongListview;
        public void TongTienHDNhap()
        {
            try
            {
                double k = 0;
                Entities.ChiTietPhieuTTCuaKH[] f = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                for (int i = 0; i < f.Length; i++)
                {
                    k += double.Parse(f[i].ThanhToan.ToString());
                    TongTienTrongListview = k;
                }
            }
            catch
            {
            }
        }

        public void dgvHienThi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                for (int i = 0; i < param.Length; i++)
                {
                    if (param[i].MaHDBanHang == dgvHienThi.CurrentRow.Cells["MaHDBanHang"].Value.ToString())
                    {
                        save = param[i];
                    }
                }
                txtMaHoaDon.Text = save.MaHDBanHang;
                txtTongTien.Text = Common.Utilities.FormatMoney(save.TongTienThanhToan);
                txtSoTienNo.Text = Common.Utilities.FormatMoney(save.SoNo);
                txtThanhToan.Text = Common.Utilities.FormatMoney(save.ThanhToan);
            }
            catch
            {

            }
        }

        public void DeleteRow()
        {
            try
            {
                hienthi1 = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi1 == null)
                    return;
                // obj = null
                if (save == null)
                    return;
                param = new Entities.ChiTietPhieuTTCuaKH[hienthi1.Length - 1];
                int sotang = 0;
                for (int j = 0; j < hienthi1.Length; j++)
                {
                    if (hienthi1[j].MaHDBanHang != save.MaHDBanHang)
                    {
                        param[sotang] = new Entities.ChiTietPhieuTTCuaKH(Common.Constants.Insert, hienthi1[j].MaHDBanHang, SbiMaPTTKH.Text.ToString(), hienthi1[j].TongTienThanhToan, hienthi1[j].SoNo, hienthi1[j].ThanhToan, hienthi1[j].ThanhToanMoi);
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = param;
                //lbTongBanGhi.Text = Common.Constants.TongSo + dgvHienThi.Items.Count;
                save = null;
            }
            catch
            {


            }

        }

        public void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                DeleteRow();
            }
            catch
            {
            }
        }

        string mahanghoa;
        string maHDBanbuon;
        public double soluongmoi;
        public double soluongcu;
        public double soluonghientai;

        public void NewRow()
        {
            try
            {
                int sohangtrongbang;
                hienthi1 = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                // list view = null
                if (hienthi1 == null)
                {
                    string sl = "0";
                    if (txtThanhToan.Text == "")
                        sl = "0";
                    else
                        sl = txtThanhToan.Text;
                    string soluongsp = sl;
                    param = new Entities.ChiTietPhieuTTCuaKH[1];

                    param[0] = new Entities.ChiTietPhieuTTCuaKH(Common.Constants.Insert, txtMaHoaDon.Text, SbiMaPTTKH.Text.ToString(), txtTongTien.Text, txtSoTienNo.Text, sl, thanhtoanmoi);
                    param[0].MaPhieuTTCuaKH = lbMaPhieuTTKH.Text.ToString();
                    dgvHienThi.DataSource = param;
                    return;
                }

                sohangtrongbang = hienthi1.Length;
                // số lượng bảng ghi khác 0
                if (sohangtrongbang != 0)
                {
                    for (int j = 0; j < sohangtrongbang; j++)
                    {
                        // nếu tìm được mã đã có trong list view
                        if (mahanghoa == hienthi1[j].MaHDBanHang)
                        {
                            param = new Entities.ChiTietPhieuTTCuaKH[sohangtrongbang];
                            break;
                        }
                        // nếu không tìm được
                        else
                            param = new Entities.ChiTietPhieuTTCuaKH[sohangtrongbang + 1];
                    }
                }
                // số lượng bảng ghi = 0
                else
                    param = new Entities.ChiTietPhieuTTCuaKH[sohangtrongbang + 1];
                // nếu số lượng bảng ghi khác 0
                if (param.Length != 0)
                {
                    try
                    {
                        // số lượng bảng ghi = số lượng row list view
                        if (param.Length == hienthi1.Length)
                        {
                            for (int j = 0; j < param.Length; j++)
                            {
                                // nếu mã = mã trong list view
                                if (mahanghoa == hienthi1[j].MaHDBanHang)
                                {
                                    soluongcu = double.Parse(hienthi1[j].ThanhToan);
                                    double sl = 0;
                                    if (txtThanhToan.Text == "")
                                        sl = 1;
                                    else
                                        sl = double.Parse(txtThanhToan.Text);
                                    //soluongmoi = sl;
                                    //soluonghientai = soluongcu + soluongmoi;
                                    MessageBox.Show(hienthi1[j].MaHDBanHang + " đã có trong chi tiết phiếu thanh toán khách hàng.", Common.MSG.TieuDe);

                                    param[j] = new Entities.ChiTietPhieuTTCuaKH(hienthi1[j].HanhDong, hienthi1[j].MaHDBanHang, SbiMaPTTKH.Text.ToString(), (txtTongTien.Text), txtSoTienNo.Text, Convert.ToString(soluongcu), thanhtoanmoi);
                                    param[j].MaPhieuTTCuaKH = lbMaPhieuTTKH.Text.ToString();
                                }
                                // nếu mã không = mã trong list view
                                else
                                {
                                    param[j] = new Entities.ChiTietPhieuTTCuaKH(hienthi1[j].HanhDong, hienthi1[j].MaHDBanHang, SbiMaPTTKH.Text.ToString(), hienthi1[j].TongTienThanhToan, hienthi1[j].SoNo, hienthi1[j].ThanhToan, hienthi1[j].ThanhToanMoi);
                                    param[j].MaPhieuTTCuaKH = lbMaPhieuTTKH.Text.ToString();
                                }

                            }
                        }
                        // số lượng bảng ghi không = số lượng row list view
                        else
                        {
                            for (int j = 0; j < param.Length; j++)
                            {
                                // lấy lại số bảng ghi trên list view
                                if (j < param.Length - 1)
                                {
                                    param[j] = new Entities.ChiTietPhieuTTCuaKH(hienthi1[j].HanhDong, hienthi1[j].MaHDBanHang, SbiMaPTTKH.Text.ToString(), hienthi1[j].TongTienThanhToan, hienthi1[j].SoNo, hienthi1[j].ThanhToan, hienthi1[j].ThanhToanMoi);
                                    param[j].MaPhieuTTCuaKH = lbMaPhieuTTKH.Text.ToString();
                                }
                                // bảng ghi cuối cùng là mới insert vào
                                else
                                {
                                    string sl = "0";
                                    if (txtThanhToan.Text == "")
                                        sl = "1";
                                    else
                                        sl = txtThanhToan.Text;
                                    string soluongsp = sl;
                                    param[param.Length - 1] = new Entities.ChiTietPhieuTTCuaKH(hienthi1[j].HanhDong, hienthi1[j].MaHDBanHang, SbiMaPTTKH.Text.ToString(), (txtTongTien.Text), (txtSoTienNo.Text), (sl), thanhtoanmoi);
                                    param[j].MaPhieuTTCuaKH = lbMaPhieuTTKH.Text.ToString();
                                }
                            }
                        }
                    }
                    catch
                    {
                        string sl = "0";
                        if (txtThanhToan.Text == "")
                            sl = "1";
                        else
                            sl = txtThanhToan.Text;
                        string soluongsp = sl;
                        param[param.Length - 1] = new Entities.ChiTietPhieuTTCuaKH(Common.Constants.Insert, txtMaHoaDon.Text, SbiMaPTTKH.Text.ToString(), (txtTongTien.Text), (txtSoTienNo.Text), (sl), thanhtoanmoi);

                    }
                    dgvHienThi.DataSource = param;
                }
            }
            catch
            {
                string sl = "0";
                if (txtThanhToan.Text == "")
                    sl = "1";
                else
                    sl = txtThanhToan.Text;
                string soluongsp = sl;
                param = new Entities.ChiTietPhieuTTCuaKH[1];
                param[0] = new Entities.ChiTietPhieuTTCuaKH(Common.Constants.Insert, txtMaHoaDon.Text, SbiMaPTTKH.Text.ToString(), (txtTongTien.Text), (txtSoTienNo.Text), (sl), thanhtoanmoi);

                dgvHienThi.DataSource = param;
            }
            finally
            {
                fix();
            }
        }

        void fix()
        {
            for (int i = 0; i < dgvHienThi.ColumnCount; i++)
            {
                dgvHienThi.Columns[i].Visible = false;
            }

            dgvHienThi.Columns["MaHDBanHang"].HeaderText = "Mã Hóa Đơn";
            dgvHienThi.Columns["MaHDBanHang"].Visible = true;
            dgvHienThi.Columns["TongTienThanhToan"].HeaderText = "Tổng Tiền Thanh Toán";
            dgvHienThi.Columns["TongTienThanhToan"].Visible = true;
            dgvHienThi.Columns["SoNo"].HeaderText = "Số Nợ";
            dgvHienThi.Columns["SoNo"].Visible = true;
            dgvHienThi.Columns["ThanhToan"].HeaderText = "Thanh Toán";
            dgvHienThi.Columns["ThanhToan"].Visible = true;
            if (dgvHienThi.RowCount > 0)
            {
                dgvHienThi.Focus();
                dgvHienThi.Select();
            }
            dgvHienThi.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
        }

        #endregion

        #region form xư lý phiếu thanh toán khách hàng

        // xu ly khi sua
        public frmXuLy(Entities.PhieuTTCuaKH phieuthanhtoankhachhang, string hanhdong)
        {
            InitializeComponent();
            try
            {
                //
                this.hanhdong = hanhdong;
                panel_TinhToan.Enabled = false;
                panel_ChiTiet.Enabled = false;
                dgvHienThi.Enabled = false;
                btnGhiLai.Enabled = false;
                temp = phieuthanhtoankhachhang;
                phieuthanhtoankh = phieuthanhtoankhachhang;

                // Status Bar
                SbiMaPTTKH.Text = phieuthanhtoankhachhang.MaPhieuTTCuaKH;

                // hiển thị phiếu TTKH
                XuLyDuLieu(phieuthanhtoankhachhang);

                //
                GetDataComBoLoaiPhieu();
                HienThiComBoBoxLoaiPhieu(phieuthanhtoankhachhang.LoaiPhieu.ToString());

                // hiển thị chi tiết phiếu TTKH
                dgvHienThi.DataSource = HienThiChiTiet(phieuthanhtoankh);
                fix();

            }
            catch
            {
            }

        }

        // xu ly khi them
        public frmXuLy(string hanhdong)
        {
            InitializeComponent();
            try
            {
                this.hanhdong = hanhdong;
                btnIn.Enabled = false;
                SbiMaPTTKH.Text = getID();
                lbMaPhieuTTKH.Text = getID();

                //
                GetDataComBoLoaiPhieu();
            }
            catch
            { }
        }

        // khi select 
        public string ThanhToanKhiLapPhieu1(string maHDBanbuon)
        {
            Entities.HDBanBuon[] hienthiHDBanBuon = Common.StaticVariable.InterfaceObject.SelectHDBanBuonTheoMaHDBanBuon(maHDBanbuon);
            Entities.KhachHangTraLaiBanBuon[] htKHtralaiBanBuon = Common.StaticVariable.InterfaceObject.SelectHDKHTraLaiBanBuonTheoMaKH(txtMaKH.Text);

            try
            {
                if (cbbLoaiPhieu.Text == "Phiếu Thu")
                {
                    for (int i = 0; i < hienthiHDBanBuon.Length; i++)
                    {
                        if (hienthiHDBanBuon[i].MaHDBanBuon == maHDBanbuon)
                            return hienthiHDBanBuon[i].ThanhToanSauKhiLapPhieu;
                    }
                }
                else
                {
                    for (int i = 0; i < htKHtralaiBanBuon.Length; i++)
                    {
                        if (htKHtralaiBanBuon[i].MaKhachHangTraLaiBanBuon == maHDBanbuon)
                            return htKHtralaiBanBuon[i].ThanhToanSauKhiLapPhieu;
                    }
                }
                return "0";
            }
            catch
            {
                return "0";
            }
        }

        // update Hóa Đơn Bán buôn
        public void UpdateThanhToanSauKhiLapPhieu(string ma, string thanhtoansau)
        {
            try
            {
                Common.StaticVariable.InterfaceObject.UpdateTTHDBB(ma, thanhtoansau);
            }
            catch
            {
            }
        }

        // update Trả Lại Khách Hàng
        public void UpdateThanhToanSauKhiLapPhieu(string ma, string thanhtoansau, string loai)
        {
            try
            {
                Common.StaticVariable.InterfaceObject.UpdateKHTraLai(ma,thanhtoansau, loai);
            }
            catch
            {
            }
        }


        #endregion

        #region Sự kiện MouseDown chung
        void MouseDown_Chung(object sender, MouseEventArgs e)
        {
            try
            {
                Button temp = (Button)sender;
                switch (temp.Name)
                {
                    case Common.Constants.btnThoat:
                        {
                            Thoat();
                            //  thanhtoanmoi = "0";
                            break;
                        }
                    case Common.Constants.btnGhiLai:
                        {
                            if (hanhdong == Common.Constants.Insert)
                            {
                                checklistview = (Entities.ChiTietPhieuTTCuaKH[])dgvHienThi.DataSource;
                                Them();
                            }
                            break;
                        }
                    case Common.Constants.btnIn:
                        {
                            In();
                            break;
                        }
                    default: break;
                }
            }
            catch
            {
            }

        }
        #endregion

        #region Control Event

        #region KeyDown

        private void txtMaKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtTenKH.Focus();
            }
            if (e.KeyCode == Keys.F4)
            {
                try
                {
                    // Dư nợ có thể âm
                    TimKiem.frmTimKiemKhachHang a = new TimKiem.frmTimKiemKhachHang();
                    a.ShowDialog();
                    if (TimKiem.frmTimKiemKhachHang.khachhang != null)
                    {
                        txtMaKH.Text = TimKiem.frmTimKiemKhachHang.khachhang.MaKhachHang;
                        txtTenKH.Text = TimKiem.frmTimKiemKhachHang.khachhang.Ten;
                        txtNoHienThoi.Text = Common.Utilities.FormatMoney(TimKiem.frmTimKiemKhachHang.khachhang.DuNo);
                        TimKiem.frmTimKiemKhachHang.khachhang = null;
                        txtNguoiNopTien.Focus();
                    }
                }
                catch 
                {
                }
             
            }
        }

        private void txtTenKH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtNguoiNopTien.Focus();
            }
        }

        private void txtMaHoaDon_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtTongTien.Focus();
            }
            if (e.KeyCode == Keys.F4)
            {
                if (txtMaKH.Text != "<F4 - Tra cứu>")
                {
                    try
                    {
                        // điều kiện để load HDBanBuon là (ThanhToanNgay + ThanhToanSauKhiLapPhieu )  < Tổng tiền  and theo MaNhanVien
                        if (cbbLoaiPhieu.Text == "Phiếu Thu") // Hóa đơn bán buôn
                        {
                            TimKiem.frmHoaDonBanBuon a = new TimKiem.frmHoaDonBanBuon(txtMaKH.Text, false);
                            a.ShowDialog();
                            if (TimKiem.frmHoaDonBanBuon.hdbanbuon != null)
                            {
                                txtMaHoaDon.Text = TimKiem.frmHoaDonBanBuon.hdbanbuon.MaHDBanBuon;
                                txtTongTien.Text = Common.Utilities.FormatMoney(TimKiem.frmHoaDonBanBuon.hdbanbuon.TongTienThanhToan);
                                double trangay = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.ThanhToanNgay);
                                double trasau = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.ThanhToanSauKhiLapPhieu);
                                double tongtien = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.TongTienThanhToan);
                                double thevip = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.GiaTriThe);

                                double tienno = (tongtien - (trangay + trasau + thevip));
                                txtSoTienNo.Text = Common.Utilities.FormatMoney(tienno.ToString());
                                TimKiem.frmHoaDonBanBuon.hdbanbuon = null;
                                txtThanhToan.Focus();

                            }
                        }

                        if (cbbLoaiPhieu.Text == "Phiếu Chi") // Hóa đơn KH trả lại bán buôn
                        {
                            TimKiem.frmHoaDonBanBuon a = new TimKiem.frmHoaDonBanBuon(txtMaKH.Text, true);
                            a.ShowDialog();
                            if (TimKiem.frmHoaDonBanBuon.hdbanbuon != null)
                            {
                                txtMaHoaDon.Text = TimKiem.frmHoaDonBanBuon.hdbanbuon.MaHDBanBuon;
                                txtTongTien.Text = Common.Utilities.FormatMoney(TimKiem.frmHoaDonBanBuon.hdbanbuon.TongTienThanhToan);
                                double trangay = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.ThanhToanNgay);
                                double trasau = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.ThanhToanSauKhiLapPhieu);
                                double tongtien = double.Parse(TimKiem.frmHoaDonBanBuon.hdbanbuon.TongTienThanhToan);

                                double tienno = (tongtien - (trangay + trasau));
                                txtSoTienNo.Text = Common.Utilities.FormatMoney(tienno.ToString());
                                TimKiem.frmHoaDonBanBuon.hdbanbuon = null;
                                txtThanhToan.Focus();

                            }
                        }
                    }
                    catch 
                    {
                    }
          
                }
                else { MessageBox.Show(Common.MSG.MSG13(lbMaKH.Text.ToString()),Common.MSG.TieuDe);
                txtMaKH.Focus();
                }
            }
        }
      
        private void txtNguoiNopTien_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtGhiChu.Focus();
            }
        }

        private void txtSoTienConNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtThanhToan.Focus();
            }
        }

        private void txtNoHienThoi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtTongTien.Focus();
            }
        }

        private void txtTongTien_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtSoTienNo.Focus();
            }
        }

        private void txtGhiChu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtMaHoaDon.Focus();
            }
        }

        #endregion

        #region xử lý ID
        #region GetID
        public string getID()
        {
            string code = string.Empty;
            try
            {
                Entities.GetID id = new Entities.GetID();
                id.TableName = "PhieuTTCuaKH";
                Entities.GetID get = Common.StaticVariable.InterfaceObject.SelectID(id);

                if (get.ColumnName != null)
                {
                    code = Common.Utilities.ProcessID(get.ColumnName);
                }
                else
                { code = "PTTKH_0001"; }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                code = "PTTKH_0001";
            }
            return code;
        }
        #endregion
        #endregion

        #region check validate

        public bool Validate()
        {
            try
            {
                if (txtMaKH.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaKH.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaKH.Focus();
                    return false;
                }
                //if (txtMaHoaDon.Text == "<F4 - Tra cứu>")
                //{
                //    MessageBox.Show(Common.MSG.MSG13(lbMaHoaDon.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                //    txtMaHoaDon.Focus();
                //    return false;
                //}
                if (txtTenKH.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbTenKH.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtTenKH.Focus();
                    return false;
                }
                if (txtNoHienThoi.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbNoHienThoi.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtNoHienThoi.Focus();
                    return false;
                }
                if (txtNguoiNopTien.Text == "")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbNguoiNopTien.Text.ToString()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtNguoiNopTien.Focus();
                    return false;
                }

                return true;

            }
            catch 
            {
                return true;
                
            }
          
        }

        #endregion

        #region Xử lý dữ liệu
        public void XuLyDuLieu(Entities.PhieuTTCuaKH phieuthanhtoankh)
        {
            try
            {
                lbMaPhieuTTKH.Text = phieuthanhtoankh.MaPhieuTTCuaKH;
                txtMaKH.Text = phieuthanhtoankh.MaKhachHang;
                txtTenKH.Text = phieuthanhtoankh.TenKhachHang;
                txtNoHienThoi.Text = Common.Utilities.FormatMoney(phieuthanhtoankh.NoHienThoi);
                txtNguoiNopTien.Text = phieuthanhtoankh.NguoiNop;
                cbbLoaiPhieu.SelectedValue = phieuthanhtoankh.LoaiPhieu;
                txtGhiChu.Text = phieuthanhtoankh.GhiChu;

            }
            catch 
            {
                
                
            }

        }
        #endregion

        #region Xử lý đối tượng
        // Insert data of phiếu thanh toán khách hàng into database
        public Entities.PhieuTTCuaKH XuLyObject(string hanhdong)
        {
            try
            {
                if (Validate())
                {
                    Entities.PhieuTTCuaKH phieuttkh = new Entities.PhieuTTCuaKH();

                    phieuttkh.HanhDong = hanhdong;
                    phieuttkh.MaPhieuTTCuaKH = lbMaPhieuTTKH.Text.ToString();
                    phieuttkh.NgayLap = DateTime.Parse(Common.StaticVariable.InterfaceObject.SelectDate().ToString("MM/dd/yyyy"));
                    phieuttkh.MaKhachHang = txtMaKH.Text.ToString();
                    phieuttkh.TenKhachHang = txtTenKH.Text.ToString();
                    phieuttkh.MaNhanVien = UtilitiesVariable.User.MaNhanVien;

                    phieuttkh.MaKho = Entitystatic.ViewFile().MaKho;
                    
                    phieuttkh.TongThanhToan = lbTongThanhToan.Text.ToString();
                    phieuttkh.NoHienThoi = txtNoHienThoi.Text;
                    phieuttkh.NguoiNop = txtNguoiNopTien.Text.ToString();
                    if (cbbLoaiPhieu.SelectedValue.ToString() == "True")
                    {
                        phieuttkh.LoaiPhieu = true;
                    }
                    else
                    {
                        phieuttkh.LoaiPhieu = false;
                    }

                    phieuttkh.GhiChu = txtGhiChu.Text.ToString();
                    phieuttkh.Deleted = false;
                    phieuttkh.TaiKhoan = UtilitiesVariable.User;

                    return phieuttkh;
                }
                return null;
            }
            catch
            {
                return null;
            }

        }
        #endregion

        public void txtThanhToan_TextChanged(object sender, EventArgs e)
        {
            try
            {
                double thanhtoan = double.Parse(txtThanhToan.Text);
                double sono = double.Parse(txtSoTienNo.Text);
              
                if (thanhtoan <= 0 || thanhtoan > sono)
                {
                    txtThanhToan.Text = txtSoTienNo.Text;
                }
                else
                {
                    TextBox temp = (TextBox)sender;
                    int vt = temp.SelectionStart;
                    string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());

                    temp.Text = Common.Utilities.FormatMoney(str);
                    temp.SelectionStart = vt;
                }
            }
            catch
            {
                txtThanhToan.Text = "";
            }
        }

        private void txtMaKH_MouseLeave(object sender, EventArgs e)
        {
            if (txtMaKH.Text == "")
            {
                txtMaKH.Text = "<F4 - Tra cứu>";
            }
        }

        private void txtMaKH_MouseMove(object sender, MouseEventArgs e)
        {
            if (txtMaKH.Text == "<F4 - Tra cứu>")
            {
                txtMaKH.Text = "";
            }

        }

        private void txtMaHoaDon_MouseLeave(object sender, EventArgs e)
        {
            if (txtMaHoaDon.Text == "")
            {
                txtMaHoaDon.Text = "<F4 - Tra cứu>";
            }
        }

        private void txtMaHoaDon_MouseMove(object sender, MouseEventArgs e)
        {
            if (txtMaHoaDon.Text == "<F4 - Tra cứu>")
            {
                txtMaHoaDon.Text = "";
            }
        }

        private void txtNguoiNopTien_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                Common.ValidateControl.CheckNumber(e);
            }
            catch
            {
            }
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            Add_GridView();
        }

        #endregion

       

    }
}
